//
//  SelectPersonViewController.m
//  PhotographyStudi
//
//  Created by 一枫 on 2017/8/4.
//  Copyright © 2017年 叶一枫. All rights reserved.
//

#import "SelectPersonViewController.h"

@interface SelectPersonViewController ()<UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate>

@property (nonatomic,strong)NSMutableArray *personArr;//所有好友列表
@property (nonatomic,strong)NSMutableArray *selectedArr;//选择好友列表
@property (nonatomic,strong)NSMutableArray *resultArray;//搜索数组

@property (nonatomic,strong)UISearchController *searchController;
@property (nonatomic,assign)BOOL isSearching;


@end

@implementation SelectPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self getFriend];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(selectedComplet)];
    [self initSearchController];
}

-(void)getFriend{
    
//    [[BSRequest shareBSRequest]postMessageWithUrl:MYFRIEND parameter:@{@"uid":[User shareUser].uid} requestBlock:^(BSRequestMode *RequestMode) {
//        if ([RequestMode.state isEqualToString:@"1"]) {
//
//            [self.personArr removeAllObjects];
//
//            for (NSDictionary *userInfo in [RequestMode.modelDic objectForKey:@"list_info"]) {
//                User *user = [[User alloc]init];
//                user.uname = [[userInfo objectForKey:@"user_info"] objectForKey:@"user_name"];
//                user.ename = [[[userInfo objectForKey:@"user_info"] objectForKey:@"org"]isEqualToString:@""]?@"尚未填写工作室":[userInfo objectForKey:@"org"];
//                user.uid = [[userInfo objectForKey:@"user_info"] objectForKey:@"uid"];
//                user.isSelected = NO;
//                [self.personArr addObject:user] ;
//            }
//
//            [self.tableView reloadData];
//        }else{
//            [MBProgessHUD_BS showTextModeInView:self.view andText:RequestMode.msg];
//        }
//    }];
}

-(void)initSearchController{

    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.barTintColor = [UIColor colorWithHexString:@""];
    self.searchController.delegate = self;
    self.searchController.searchBar.delegate = self;
    self.searchController.searchBar.placeholder = @"搜索";
    self.searchController.searchBar.searchBarStyle = UISearchBarStyleDefault;
    self.tableView.tableHeaderView = self.searchController.searchBar;
}

-(NSMutableArray *)personArr{
    if (!_personArr) {
        _personArr = [NSMutableArray array];
    }
    return _personArr;
}

-(NSMutableArray *)selectedArr{
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    return _selectedArr;
}

-(NSMutableArray *)resultArray{
    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}

-(void)selectedComplet{

    if (self.selectedArr.count<=0) {
//        [MBProgessHUD_BS showTextModeInView:self.view andText:@"未选择人员"];
        return;
    }
    
    NSMutableArray *userIds = [NSMutableArray array];
    NSString *discussionName = @"";
    for (User *user in self.selectedArr) {
        [userIds addObject:user.uid];
        discussionName = [[discussionName stringByAppendingString:@","]stringByAppendingString:user.uname];
    }
    discussionName = [discussionName substringFromIndex:1];
    
    if ([self.title isEqualToString:@"我的好友"]) {
        if (self.selectedArr.count>1) {
            [[RCIM sharedRCIM]createDiscussion:discussionName userIdList:userIds success:^(RCDiscussion *discussion) {
                [self starGroupChat:discussion];
            } error:^(RCErrorCode status) {
//                [MBProgessHUD_BS showTextModeInView:self.view andText:[NSString stringWithFormat:@"创建讨论组失败:error=%ld", (long)status]];
            }];
        }else{

            [self starSingleChat:self.selectedArr[0]];
        }
    }else if ([self.title isEqualToString:@"我的作品"]){
    
    
    }else{
    
    
    }
}

-(void)starSingleChat:(User*)user{

    ChatViewController *chat = [[ChatViewController alloc]init];
    chat.conversationType = ConversationType_PRIVATE;
    chat.needToRootVC = YES;
    chat.targetId = user.uid;
    chat.title = user.uname;
    [self.navigationController pushViewController:chat animated:YES];
}

-(void)starGroupChat:(RCDiscussion*)discussion{
    dispatch_async(dispatch_get_main_queue(), ^{
        ChatViewController *chat = [[ChatViewController alloc]init];
        chat.needToRootVC = YES;
        chat.conversationType = ConversationType_DISCUSSION;
        chat.targetId = discussion.discussionId;
        chat.title = discussion.discussionName;
        [self.navigationController pushViewController:chat animated:YES];
    });
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.isSearching?self.resultArray.count:self.personArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SelectPersonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    if (!cell) {
//        cell = [[SelectPersonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell" UIType:DETAILCELL];
//    }
//    User *user = self.isSearching?self.resultArray[indexPath.row]:self.personArr[indexPath.row];
//    [cell loadModel:user type:@"model"];
//
//    if (user.isSelected) {
//        user.isSelected = YES;
//        cell.itemImageView.image = [UIImage imageNamed:@"Selected"];
//    }else{
//        user.isSelected = NO;
//        cell.itemImageView.image = [UIImage imageNamed:@"Deselected"];
//    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    User *user = self.isSearching?self.resultArray[indexPath.row]:self.personArr[indexPath.row];
    SelectPersonCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    if (user.isSelected) {
//        user.isSelected = NO;
//        cell.itemImageView.image = [UIImage imageNamed:@"Deselected"];
//        [self.selectedArr removeObject:self.personArr[indexPath.row]];
//    }else{
//        user.isSelected = YES;
//        cell.itemImageView.image = [UIImage imageNamed:@"Selected"];
//        [self.selectedArr addObject:self.personArr[indexPath.row]];
//    }
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{

    


}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if ([searchText isEqualToString:@""]) {
        self.isSearching = NO;
    }else{
        self.isSearching = YES;
    }
    
    //需要事先情况存放搜索结果的数组
    [self.resultArray removeAllObjects];
    
    //加个多线程，否则数量量大的时候，有明显的卡顿现象
    //这里最好放在数据库里面再进行搜索，效率会更快一些
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if (searchText!=nil && searchText.length>0) {
            
            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
            for (User *user in self.self.personArr) {
                for (NSString *text in @[user.uname,user.ename]) {
                    NSString *pinyin = [[BSTool sharedBSTool]transformToPinyin:text];
                    if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
                        if (![self.resultArray containsObject:user]) {
                            [self.resultArray addObject:user];
                        }
                    }
                }
            }
        }else{
            self.resultArray = [NSMutableArray arrayWithArray:self.personArr];
        }
        //回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    });
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
